import urllib.request
import urllib.parse

# 构造请求 URL
url = "https://kyfw.12306.cn/lcquery/queryG?"
time = input("请您的出行时间：")
# 郑州东  北京西 上海
start = str(input("请输入您的出发地："))
end = input("请输入您的目的地：")
print(f"您的出行时间为{time}，您所选择的出发地是：{start}，目的地是：{end}")
# 读取车站代码文件
station_codes = {}
try:
    with open("station_code.txt", "r", encoding="utf-8") as file:
        for line in file:
            parts = line.strip().split(":")
            if len(parts) == 2:
                station_codes[parts[0].strip()] = parts[1].strip()
except FileNotFoundError:
    print("未找到车站代码文件，请确保文件存在。")
    exit(1)

# 获取车站代码
start_code = station_codes.get(start)
end_code = station_codes.get(end)
# purpose_codes = input("是否需要学生票：Y/N")
# if purpose_codes == "Y":
#     purpose_codes = "0X"
#     print("您选择的票为学生票")
# else:
#     purpose_codes = "00"
params = {
    "train_date": time,
    "from_station_telecode": start_code,
    "to_station_telecode": end_code,
    "middle_station": "",
    "result_index": "0",
    "can_query": "Y",
    "isShowWZ": "N",
    "purpose_codes": 00,
    "channel": "E"
}
# 编码参数
query_string = urllib.parse.urlencode(params)

# 构造完整的 URL
url = f"https://kyfw.12306.cn/lcquery/queryG?{query_string}"
# 设置请求头
headers = {
"referer":"https://www.12306.cn/index/view/infos/sale_time.html",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
                  "(KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0"
}

# 创建请求对象
request = urllib.request.Request(url=url, headers=headers)

# 发送请求并获取响应
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")

# 打印响应内容
# print(html)

with open("12306.json", "w", encoding="utf-8") as fp:
    fp.write(html)
import json
import jsonpath

with open("12306.json", "r", encoding="utf-8") as file:
    data = json.load(file)
    jsonpath_jsonpath = jsonpath.jsonpath(data, "$..middleStationList")
# print(jsonpath_jsonpath)
mid_station = []
for i in jsonpath_jsonpath:
    for j in i:
        mid_station.append(j.split("#")[1])
print(f"您所途径的中间站有：{mid_station}")
